package cn.kgc.tangcco.configurer;

import cn.kgc.tangcco.intercepter.CorsInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/12/25 11:05
 */
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
    @Autowired
    private CorsInterceptor corsInterceptor;

    @Autowired
    private ParamConfig paramConfig;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> corsExcludePaths = new ArrayList<>();
        corsExcludePaths.add("/res/**");
        corsExcludePaths.add("/html/**");

        List<String> atuhXcludePaths = corsExcludePaths;
        atuhXcludePaths.add("/account/sendCode");
        atuhXcludePaths.add("/account/login");

        // addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(corsInterceptor)
                .addPathPatterns(paramConfig.getPathPattern())
                .excludePathPatterns(corsExcludePaths);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(paramConfig.getPathPattern())
                // 设置允许跨域请求的域名
                .allowedOriginPatterns(paramConfig.getAccessControlAllowOrigin())
                // 是否允许证书（cookies）
                .allowCredentials(paramConfig.getAccessControlAllowCredentials().equalsIgnoreCase("true") ? true : false)
                // 设置允许的方法
                .allowedMethods(paramConfig.getAccessControlAllowMethods())
                // 跨域允许时间
                .maxAge(Integer.parseInt(paramConfig.getAccessControlAllowMaxAge()));
    }

}
